package com.lekang.le.service.impl;

import java.math.BigDecimal;
import java.util.List;
import com.lekang.common.utils.DateUtils;
import com.lekang.le.domain.ElderlySzh;
import com.lekang.le.mapper.ElderlySzhMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.lekang.le.mapper.BalanceMapper;
import com.lekang.le.domain.Balance;
import com.lekang.le.service.IBalanceService;

/**
 * 余额Service业务层处理
 * 
 * @author yyh
 * @date 2025-10-14
 */
@Service
public class BalanceServiceImpl implements IBalanceService 
{
    @Autowired
    private BalanceMapper balanceMapper;
    @Autowired
    private ElderlySzhMapper elderlySzhMapper;

    /**
     * 查询余额
     * 
     * @param id 余额主键
     * @return 余额
     */
    @Override
    public Balance selectBalanceById(Long id)
    {
        return balanceMapper.selectBalanceById(id);
    }

    /**
     * 查询余额列表
     * 
     * @param balance 余额
     * @return 余额
     */
    @Override
    public List<Balance> selectBalanceList(Balance balance)
    {
        List<Balance> balances = balanceMapper.selectBalanceList(balance);
        for(Balance bb : balances){
            Long elderlyId = bb.getElderlyId();
            ElderlySzh elderlySzh = elderlySzhMapper.selectElderlySzhById(elderlyId);
            bb.setElderly(elderlySzh);
        }
        return balances;
    }

    /**
     * 新增余额
     * 
     * @param balance 余额
     * @return 结果
     */
    @Override
    public int insertBalance(Balance balance)
    {
        return balanceMapper.insertBalance(balance);
    }

    /**
     * 修改余额
     * 
     * @param balance 余额
     * @return 结果
     */
    @Override
    public int updateBalance(Balance balance)
    {
        balance.setUpdateTime(DateUtils.getNowDate());
        return balanceMapper.updateBalance(balance);
    }

    /**
     * 预存款充值
     *
     * @param balance 余额
     * @return 结果
     */
    @Override
    public int updateBalanceAddPre(Balance balance)
    {
        BigDecimal prepaymentBalance = balance.getPrepaymentBalance();
        Balance balance1 = balanceMapper.selectBalanceById(balance.getId());
        balance.setPrepaymentBalance(balance1.getPrepaymentBalance().add(prepaymentBalance));
        balance.setUpdateTime(DateUtils.getNowDate());
        return balanceMapper.updateBalance(balance);
    }

    /**
     * 批量删除余额
     * 
     * @param ids 需要删除的余额主键
     * @return 结果
     */
    @Override
    public int deleteBalanceByIds(Long[] ids)
    {
        return balanceMapper.deleteBalanceByIds(ids);
    }

    /**
     * 删除余额信息
     * 
     * @param id 余额主键
     * @return 结果
     */
    @Override
    public int deleteBalanceById(Long id)
    {
        return balanceMapper.deleteBalanceById(id);
    }

    /**
     * 根据老人ID查询余额
     * 
     * @param elderlyId 老人ID
     * @return 余额对象
     */
    @Override
    public Balance selectBalanceByElderlyId(Long elderlyId)
    {
        return balanceMapper.selectBalanceByElderlyId(elderlyId);
    }

    /**
     * 扣除余额（用于支付订单）
     * 优先扣除预交款余额，不足时再扣除押金余额
     * 
     * @param elderlyId 老人ID
     * @param amount 扣除金额
     * @return 扣除结果（成功返回true，余额不足或失败返回false）
     */
    @Override
    public boolean deductBalance(Long elderlyId, BigDecimal amount)
    {
        // 参数校验
        if (elderlyId == null || amount == null || amount.compareTo(BigDecimal.ZERO) <= 0) {
            return false;
        }

        // 查询老人的余额记录
        Balance balance = balanceMapper.selectBalanceByElderlyId(elderlyId);
        if (balance == null) {
            return false;
        }

        // 获取当前余额（处理null值）
        BigDecimal prepaymentBalance = balance.getPrepaymentBalance();
        if (prepaymentBalance == null) {
            prepaymentBalance = BigDecimal.ZERO;
        }
        
        BigDecimal depositBalance = balance.getDepositBalance();
        if (depositBalance == null) {
            depositBalance = BigDecimal.ZERO;
        }

        // 计算总余额
        BigDecimal totalBalance = prepaymentBalance.add(depositBalance);
        
        // 判断余额是否充足
        if (totalBalance.compareTo(amount) < 0) {
            // 余额不足
            return false;
        }

        // 扣款逻辑：优先扣除预交款，不足时再扣除押金
        BigDecimal remainingAmount = amount;
        BigDecimal newPrepaymentBalance = prepaymentBalance;
        BigDecimal newDepositBalance = depositBalance;

        // 先从预交款扣除
        if (prepaymentBalance.compareTo(remainingAmount) >= 0) {
            // 预交款足够，全部从预交款扣除
            newPrepaymentBalance = prepaymentBalance.subtract(remainingAmount);
            remainingAmount = BigDecimal.ZERO;
        } else {
            // 预交款不够，预交款扣完后从押金扣除
            remainingAmount = remainingAmount.subtract(prepaymentBalance);
            newPrepaymentBalance = BigDecimal.ZERO;
            newDepositBalance = depositBalance.subtract(remainingAmount);
        }

        // 更新余额
        balance.setPrepaymentBalance(newPrepaymentBalance);
        balance.setDepositBalance(newDepositBalance);
        balance.setUpdateTime(DateUtils.getNowDate());
        
        int result = balanceMapper.updateBalance(balance);
        return result > 0;
    }
}
